$(document).ready(function () {
    /**
     *event.persisted 判断浏览器是否有缓存, 有为true, 没有为false
     */
    window.addEventListener('pageshow', function (event) {
        if (event.persisted || window.performance && window.performance.navigation.type == 2) {
            location.reload();
        }
    }, false);

    /**
     * 展开/收起下拉列表
     */
    $('.option').click(function () {
        $(this).children('.option_list').slideToggle(100);
        $(this).toggleClass('active');
    });

    /**
     * 设置option的值
     */
    $('.option_list li').click(function () {
        //获取选择的值
        var text = $(this).text();

        //设置option的值
        $(this).parent().siblings('.option_result').text(text);
    });
    /**
     * 为每个算法列表项添加点击事件
     */
    var algorithmItems = document.querySelectorAll("#predictionAlgorithm li");
    algorithmItems.forEach(function (item) {
        item.addEventListener("click", function () {
            // 移除所有算法列表项的选中状态
            algorithmItems.forEach(function (item) {
                item.classList.remove("selected");
            });
            // 添加当前点击的算法列表项的选中状态
            this.classList.add("selected");
        });
    });

});

/**
 * 预测按钮
 */
function predictStock_two() {

    let stockCode = document.getElementById("stockCode").value.trim();
    let selectedAlgorithm = document.querySelector("#predictionAlgorithm li.selected");

    // 如果股票代码为空，则弹窗提示并返回
    if (stockCode === "") {
        alert("未填写股票代码");
        return;
    }

    /**
     *  如果没有选择预测算法，默认为第一种算法
     */
    let predictionAlgorithm = "LSTM";
    // if (selectedAlgorithm) {
    //     predictionAlgorithm = selectedAlgorithm.getAttribute("data-value");
    // }
    // 构造要发送的数据
    let requestData = {
        stockCode: stockCode,
        predictionAlgorithm: predictionAlgorithm
    };

    let twoDecimal = (num) => {
        let multiplied = num * 100;
        let rounded = Math.round(multiplied);
        return rounded / 100
    }


    $.ajax({
        url: host + "/api/test",
        type: "get",
        data: {
            stock_code: requestData.stockCode,
            // model: requestData.predictionAlgorithm,
            // length: 365 * 2
        },
        success: function (res) {
            let arr = [] //这个数组存的事K线图的数据
            let trendArr = [] //这个数组存的是趋势图的数据

            trendArr.push(["Income", "Country", "Year"])
            let length = res.data.close.length;
            for (let i = 0; i < length; i++) {
                let arr1 = []
                let arr2 = []
                arr1.push(res.data.trade_date[i])
                arr1.push(twoDecimal(res.data.open[i]))
                arr1.push(twoDecimal(res.data.close[i]))
                arr1.push(twoDecimal(res.data.low[i]))
                arr1.push(twoDecimal(res.data.high[i]))

                arr.push(arr1)


                if (res.data.predict_high[i] !== -1 &&
                    res.data.predict_high[i] !== 0
                ) {
                    let actualHigh = res.data.high[i]
                    let actualLow = res.data.low[i]
                    let predictHigh = res.data.predict_high[i]
                    let predictLow = res.data.predict_low[i]
                    let date = res.data.trade_date[i]

                    // arr2.push(actualHigh, stockInfo.actualHigh, date)
                    // arr2.push(actualLow, stockInfo.actualLow, date)
                    // arr2.push(predictHigh, stockInfo.predictHigh, date)
                    // arr2.push(predictLow, stockInfo.predictLow, date)
                    //
                    // arr2.push((actualLow + actualHigh) / 2, stockInfo.actual, date)
                    // arr2.push((predictLow + predictHigh) / 2, stockInfo.predict, date)
                    trendArr.push([twoDecimal(predictHigh), stockInfo.predictHigh, date])
                    trendArr.push([twoDecimal(predictLow), stockInfo.predictLow, date])
                    trendArr.push([twoDecimal((predictLow + predictHigh) / 2), stockInfo.predict, date])

                    if (i >= res.data.predict_high.length - 3) continue
                    trendArr.push([twoDecimal(actualHigh), stockInfo.actualHigh, date])
                    trendArr.push([twoDecimal(actualLow), stockInfo.actualLow, date])
                    trendArr.push([twoDecimal((actualLow + actualHigh) / 2), stockInfo.actual, date])
                }


            }
            // let temp = [...trendArr[trendArr.length - 1]]
            // temp[1] = "预测"
            // trendArr.push(temp)
            // trendArr.push([res.predict, "预测", res.next_day])
            console.log(arr)
            localStorage.setItem("data", JSON.stringify(arr))
            localStorage.setItem("stockCode", res.data.ts_code[0])
            localStorage.setItem("stockName", res.meta.name)
            localStorage.setItem("stockMeta", JSON.stringify(res.meta))
            localStorage.setItem("trend", JSON.stringify(trendArr))
            console.log(trendArr)


            setTimeout(() => {
                window.open("./main.html", "_blank")
                window.location.reload();//刷新原页面
            }, 13000); //
        },
        error: function (res) {
            $("#light").css('display', 'none');
            alert("股票代码有误")
            console.log("error")
            window.location.reload();//刷新原页面，如果出问题刷新页面
        }
    })

    console.log("发送的数据:", requestData.stockCode, "model1");

}





